import { HttpException, HttpStatus, Injectable } from "@nestjs/common";
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { User } from "./entities/user.entity";
import { FindUserDTO } from "./dto/find-user.dto";
import {v4 as uuidv4} from 'uuid'
import { ConfigService } from "@nestjs/config";
@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
    private configService: ConfigService,
  ) {}
  //新增用户
  async create(createUserDto: CreateUserDto, ip) {
    const UsersBuilder = this.usersRepository.createQueryBuilder();
    const { username, password, status, birthday, realName, phone, level } = createUserDto;

    const userOne = await UsersBuilder.where("username = :username", { username }).getOne();
    if(userOne){
      throw new HttpException("此用户已存在", HttpStatus.INTERNAL_SERVER_ERROR)
    }

    if(phone){
      const userOne = await UsersBuilder.where("phone = :phone", { phone }).getOne();
      if(userOne){
        throw new HttpException("此手机号已存在", HttpStatus.INTERNAL_SERVER_ERROR)
      }
    }

    const result = await UsersBuilder.insert().into(User).values({
      username,
      password,
      ...(username && { username }),
      ...(password && { password }),
      ...(status && { status }),
      ...(birthday && { birthday }),
      ...(realName && { realName }),
      ...(phone && { phone }),
      ...(level && { level }),
      uniqueToken: uuidv4()
    }).execute()

    if(result.identifiers.length >0){
      return result.identifiers
    }
    throw new HttpException("添加用户失败", HttpStatus.INTERNAL_SERVER_ERROR)
  }
  /**
   * 查询所有用户
   * @param findUserDto
   */
  async findAll(findUserDto:FindUserDTO) {
    const UsersBuilder = this.usersRepository.createQueryBuilder();
    //用户
    if(findUserDto.username){
      UsersBuilder.andWhere("username LIKE :username", { username:  `%${findUserDto.username}%` })
    }
    //真实姓名
    if(findUserDto.realName){
      UsersBuilder.andWhere("realName = :realName", { realName:  findUserDto.realName })
    }
    //手机号
    if(findUserDto.phone){
      UsersBuilder.andWhere("phone = :phone", {phone: findUserDto.phone})
    }
    //状态
    if(findUserDto.status){
      UsersBuilder.andWhere("status = :status", {status: findUserDto.status})
    }
    const [list,total] = await UsersBuilder.orderBy('id','DESC').skip((findUserDto.page -1) *findUserDto.pageSize).take(findUserDto.pageSize).getManyAndCount()
    list.forEach(item=>{
      delete item.password
    })
    return {
      list,
      total
    }
  }

  findOne(id: number) {
    return `This action returns a #${id} user`;
  }

  async update( updateUserDto: UpdateUserDto) {
    const UsersBuilder = this.usersRepository.createQueryBuilder();
    const {realName, phone , status , level , birthday, username} = updateUserDto;
    const {affected} = await UsersBuilder.update(User).set({
      ...(realName && {realName}),
      ...(phone && {phone}),
      ...(status && {status}),
      ...(level && {level}),
      ...(birthday && {birthday}),
    }).where("username = :username",{username}).execute();
    if(affected>0){
      return '操作成功'
    }
    throw new HttpException("编辑成功" , HttpStatus.INTERNAL_SERVER_ERROR)
  }

  async remove(deleteUserDto) {
    const UsersBuilder = this.usersRepository.createQueryBuilder();
    const {affected} = await UsersBuilder.update(User).set({status: 3}).whereInIds(deleteUserDto.ids).execute();
    if(affected>0){
      return '操作成功'
    }
    throw new HttpException("更新失败" , HttpStatus.INTERNAL_SERVER_ERROR)
  }

  /**
   * 返回用户唯一id
   * @param userid 用户id
   */
  async uniqueTokenBack(userid:number | string) {
    const UsersBuilder = this.usersRepository.createQueryBuilder();
    const userOne =  await UsersBuilder.where("id = :id",{id:userid}).getOne()
    if(!userOne){
      throw new HttpException("无此用户", HttpStatus.INTERNAL_SERVER_ERROR)
    }
    if(userOne.status === 2){
      throw new HttpException("此用户以封禁", HttpStatus.INTERNAL_SERVER_ERROR)
    }
    if(userOne.status === 3){
      console.log("此用户已删除");
      throw new HttpException("无此用户_", HttpStatus.INTERNAL_SERVER_ERROR)
    }
    return userOne.uniqueToken
  }
}
